package com.jiangnan.warehouse_management.controller;

import com.jiangnan.warehouse_management.common.Result;
import com.jiangnan.warehouse_management.common.exception.BusinessException;
import com.jiangnan.warehouse_management.dto.request.*;
import com.jiangnan.warehouse_management.dto.response.LoginResponse;
import com.jiangnan.warehouse_management.dto.response.LoginResponse.UserDTO;
import com.jiangnan.warehouse_management.dto.response.RegisterResponse;
import com.jiangnan.warehouse_management.dto.response.UserQueryResponse;
import com.jiangnan.warehouse_management.service.UserService;
import com.jiangnan.warehouse_management.utils.JwtUtils;
import com.jiangnan.warehouse_management.utils.MD5Utils;
import lombok.RequiredArgsConstructor;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Validated
public class UserController {

    @Autowired
    private final UserService userService;
    private final MD5Utils md5Utils;

    @PostMapping("/auth/login")
    public Result<LoginResponse> login(@RequestBody @Validated LoginRequest request) {
        // 根据用户名查找用户
        UserDTO user = userService.findByUsername(request.getUsername());
        if (user == null) {
            return Result.fail(400,"用户名不存在");
        }

        // 验证密码
        if (!md5Utils.verify(request.getPassword(), user.getPassword())) {
            return Result.fail(400,"密码错误");
        }

        // 检查用户状态
        if (!user.getStatus()) {
            return Result.fail("账号已被禁用");
        }

        // 生成JWT令牌，包含用户ID和用户名
        String token = JwtUtils.generateToken(user.getUserId(), user.getUsername(), user.getRole());

        // 构建登录响应
        LoginResponse response = new LoginResponse();
        response.setToken(token);

        LoginResponse.UserDTO userDTO = new LoginResponse.UserDTO();
        userDTO.setUserId(user.getUserId());
        userDTO.setUsername(user.getUsername());
        userDTO.setRealName(user.getRealName());
        userDTO.setPhone(user.getPhone());
        userDTO.setEmail(user.getEmail());
        userDTO.setRole(user.getRole());
        userDTO.setStatus(user.getStatus());

        response.setUser(userDTO);

        return Result.success(response);
    }

    @PostMapping("/users")
    public Result<RegisterResponse> register(@RequestBody @Validated RegisterRequest request) {
        // 检查用户名是否存在
        UserDTO user = userService.findByUsername(request.getUsername());
        if (user != null) {
            throw new BusinessException(400, "用户名已经存在");
        }

        // 执行注册
        RegisterResponse response = userService.register(request);
        if (response == null) {
            throw new BusinessException(400, "注册失败");
        }

        return Result.success(response);
    }

    @GetMapping("/users")
    public Result<UserQueryResponse> getUsers(@Validated @ModelAttribute UserQueryRequest request) {
        try {
            // 调用服务层执行查询
            UserQueryResponse response = userService.listUsers(request);
            return Result.success(response);
        } catch (Exception e) {
            return Result.fail(500, "查询失败：" + e.getMessage());
        }
    }

    @GetMapping("/userById")
    public Result<UserQueryResponse.QueryUserDTO> getSingleUser(@Validated @RequestParam("id") int id) {
        UserQueryResponse.QueryUserDTO data = userService.findById(id);
        return Result.success(data);
    }

    @PutMapping("/updateUserInfo")
    public Result<UserQueryResponse.QueryUserDTO> updateUserInfo(@Validated @RequestBody UpdateUserRequest request) {
        // 获取当前登录用户信息
        JwtUtils.CurrentUser currentUser = JwtUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.fail(401, "未登录或登录已过期");
        }

        // 设置要更新的用户ID
        request.setUserId(currentUser.getUserId());
        
        // 执行更新
        UserQueryResponse.QueryUserDTO data = userService.updateUserInfo(request);
        if (data == null) {
            return Result.fail(400, "更新失败");
        }
        
        return Result.success(data);
    }

    @PostMapping("/updateUserPwd")
    public Result<?> updateUserPwd(@Validated @RequestBody UpdatePasswordRequest request) {
        // 获取当前登录用户信息
        JwtUtils.CurrentUser currentUser = JwtUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.fail(401, "未登录或登录已过期");
        }

        try {
            userService.updateUserPwd(currentUser.getUserId(), request);
            return Result.success("密码修改成功");
        } catch (BusinessException e) {
            return Result.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return Result.fail(500, "密码修改失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/deleteUser")
    public Result<?> deleteUser(@RequestParam("id") int id) {
        // 获取当前登录用户信息
        JwtUtils.CurrentUser currentUser = JwtUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.fail(401, "未登录或登录已过期");
        }

//        System.out.println(currentUser.getRole());
//        String role = currentUser.getRole().trim().toLowerCase();
//        // 检查权限：只有管理员可以删除用户
//        if (!"admin".equals(role)){
//            System.out.println("1" + currentUser.getRole());
//            return Result.fail(403, "没有权限执行此操作");
//        }

        try {
            userService.deleteUser(id);
            return Result.success("删除成功");
        } catch (Exception e) {
            return Result.fail(500, "删除失败：" + e.getMessage());
        }
    }
}